package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.DisplayFenlei;
import com.qianniu.napi.admin.entity.GoodsCategory;
import com.qianniu.napi.admin.entity.MerchantConfig;
import com.qianniu.napi.admin.entity.Nav;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.ResourceActor;
import com.qianniu.napi.common.util.ObjectUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2018-06-23
 */
@Controller
public class GoodsCategoryController {

    private static final Logger logger = LoggerFactory.getLogger(GoodsCategoryController.class);

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private INavService navService;
    @Autowired
    private IGoodsCategoryService goodscategoryService;
    @Autowired
    private IMerchantConfigService merchantConfigService;
    @Autowired
    private IMerchantConfigService mcService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IDisplayFenleiService displayFenleiService;

    @RequiresPermissions("admin:user:view")
    @RequestMapping("admin/goodscategory/index")
    public String index(Model model) {

        List<GoodsCategory> cates = goodscategoryService.selectList(new EntityWrapper<GoodsCategory>()
                .setSqlSelect("id,name")
                .eq("mpid", ObjectUtil.getMpid())
                .eq("level", 1)
                .orderBy("createtime", false)
        );
        model.addAttribute("cates", cates);
        return "admin/goodscategory";
    }

    @RequiresPermissions("admin:user:view")
    @RequestMapping("/admin/goodscategory/list")
    @ResponseBody
    public Page<GoodsCategory> list(Model model,
                                    @RequestParam(value = "offset", required = false) Integer offset,
                                    @RequestParam(value = "status", required = false) Integer status,
                                    @RequestParam(value = "search", required = false) String search,
                                    @RequestParam(value = "limit", required = false) Integer limit) {
        Wrapper<GoodsCategory> wrapper = new EntityWrapper<GoodsCategory>();/*.eq("uid",ObjectUtil.getUid());*/
        int utype = ObjectUtil.getUserType();
        if (utype < 39)
            wrapper.eq("mpid", ObjectUtil.getMpid());
        else if (utype < 99)
            wrapper.eq("mid", ObjectUtil.getMid());
//        wrapper.eq("state", 1);
//        if (status != 99) wrapper.eq("xftype", status);
        if (!Strings.isNullOrEmpty(search))
            wrapper.andNew().like("name", search);

        wrapper.orderBy("paixu", true);
        model.addAttribute("isAdmin", ObjectUtil.getIsAdmin());
        Page<GoodsCategory> page = goodscategoryService.selectPage(new Page<GoodsCategory>(offset / limit + 1, limit), wrapper);

        return page;
    }

    @RequestMapping("/admin/goodscategory/add")
    public String add(@Valid GoodsCategory bean, BindingResult bindingResult,Model model) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }

        if (bean.getPid() == null || bean.getPid().equals(0)) {
            bean.setLevel(0);
        } else {
            GoodsCategory parentCategory = bean.selectById(bean.getPid());
            bean.setLevel(parentCategory.getLevel() + 1);
            bean.setPname(parentCategory.getName());
        }

        bean.setKey(UUID.randomUUID().toString());
        bean.setIsNav(-1);
        bean.setCreatetime(new Date());

        if (bean.getPid() == null) {
            bean.setLevel(1);
            bean.setHasChild(-1);
        } else {
            GoodsCategory gc = goodscategoryService.selectById(bean.getPid());
            bean.setPid(gc.getLevel() + 1);
            gc.setHasChild(1);
            gc.updateById();
            bean.setHasChild(-1);
        }

        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());
        bean.setUid(ObjectUtil.getUid());
        bean.insert();
        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("GoodsCategory@"+bean.getId()+"@insert", ActorRef.noSender());

        // 默认添加到首页分类栏目
        if(bean.getLevel()==1){
            DisplayFenlei fenlei = new DisplayFenlei();
            fenlei.setCid(bean.getId());
            fenlei.setMval(bean.getId().toString());
            fenlei.setMkey("cid");
            fenlei.setMtype(1);// tab页类型
            fenlei.setMpath("/pages/category/category");// 默认分类页

            fenlei.setName(bean.getName());
            fenlei.setShowname(bean.getName());
            fenlei.setState(-1);
            fenlei.setType(8);// 默认食物商品
            fenlei.setListtype(3);//4+1样式

            fenlei.setSort(displayFenleiService.selectCount(new EntityWrapper<DisplayFenlei>().eq("mpid",bean.getMpid()))+1);

            fenlei.setUid(bean.getUid());
            fenlei.setMid(bean.getMid());
            fenlei.setMpid(bean.getMpid());
            fenlei.setCreatetime(new Date());
            fenlei.insert();
        }

        List<GoodsCategory> cates = goodscategoryService.selectList(new EntityWrapper<GoodsCategory>()
                .setSqlSelect("id,name")
                .eq("mpid", ObjectUtil.getMpid())
                .eq("level", 1)
                .orderBy("createtime", false)
        );
        model.addAttribute("cates", cates);

        return "admin/goodscategory";
    }

    @RequestMapping("/admin/goodscategory/getGoodsCategoryById")
    @ResponseBody
    public GoodsCategory getGoodsCategoryById(long id) {
        GoodsCategory goodscategory = goodscategoryService.selectById(id);
        return goodscategory;
    }

    @RequestMapping("/admin/goodscategory/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = goodscategoryService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/goodscategory/delete")
    @ResponseBody
    public int deleteBatchIds(@RequestParam(value = "ids[]") List<Integer> ids) {
        boolean isSucc = goodscategoryService.deleteBatchIds(ids);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/goodscategory/changeState")
    @ResponseBody
    public String changeState(Long id, int state) {
        GoodsCategory bean = new GoodsCategory();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        goodscategoryService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/goodscategory/changeNavState")
    @ResponseBody
    public String changeNavState(long id, int state, String pic) {
        GoodsCategory bean = new GoodsCategory();
        bean.setId(id);
        bean.setIsNav(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        goodscategoryService.updateById(bean);

        GoodsCategory gc = goodscategoryService.selectById(id);
        Nav nav = navService.selectOne(new EntityWrapper<Nav>().eq("cid", id));
        int cnt = navService.selectCount(new EntityWrapper<Nav>().eq("mid", ObjectUtil.getMid()));
        if (nav != null) return "success";
        nav = new Nav();
        nav.setName(gc.getName());
        nav.setPic(gc.getPic());
        nav.setNtype(1);// 默认1：商品分类导航
        nav.setNvalue(gc.getId().toString());
        nav.setSort(cnt + 1);
        nav.setIsSelfIcon(-1);

        nav.setMid(ObjectUtil.getMid());
        nav.setMpid(ObjectUtil.getMpid());
        nav.setUid(ObjectUtil.getUid());
        nav.setCid(gc.getId());
        nav.setState(nav.getState());
        nav.insert();

        // ****** 待完善 ******
        // 系统后台登陆获取不到appid，先默认获取第一个MerchantConfig配置
        MerchantConfig mc = mcService.selectOne(new EntityWrapper<MerchantConfig>().eq("mid", ObjectUtil.getMid()));
        if (mc != null) {
            mc.setVersion(1 + mc.getVersion());
            mc.insertOrUpdate();
        }

        return "success";
    }

    @RequestMapping("/admin/goodscategory/modify")
    public String update(GoodsCategory bean) {

        if (bean.getPid() != null) {
            GoodsCategory gc = goodscategoryService.selectById(bean.getPid());
            bean.setLevel(gc.getLevel() + 1);
            bean.setPname(gc.getName());
            gc.setHasChild(1);
            gc.updateById();
        }

        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());

        logger.debug("===================GoodsCategory update bean="+bean);
        boolean isSuccc = goodscategoryService.updateById(bean);
        if (isSuccc) {
            //更新资源文件
            AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                    .tell("GoodsCategory@"+bean.getId()+"@update", ActorRef.noSender());
            return "redirect:index";
        }
        return "error";
    }

}
